import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Table} from 'antd';
import {TABLE, DATE_FORMAT} from '../constants';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {currency} from '../Enum';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {submitData, abandonData} from './api';
import styles from './style.css';
import routes from './routes';
const {Description} = DescriptionList;

export class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
    };
    componentDidMount() {
        this.props.init();
    }
    handleUpdateClick = () => {
        this.props.history.push(routes.update.format(this.props.id));
    }
    handleConfirmClick = () => {
        this.props.history.push(routes.confirm.format(this.props.id));
    }
    handleUpInvoiceClick = () => {
        this.props.history.push(routes.upInvoice.format(this.props.id));
    }
    handleInvoiceConfirmClick = () => {
        this.props.history.push(routes.invoiceConfirm.format(this.props.id));
    }
    handleWriteOffClick = () => {
        this.props.history.push(routes.writeOff.format(this.props.id));
    }
    handleApproveClick = () => {
        this.props.history.push(routes.approve.format(this.props.id));
    }
    submitConfirm = () => {
        this.setState({loading: true});
        const rowVersion = this.props.detail.rowVersion;
        submitData(this.props.detail.id, rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    abandonConfirm = () => {
        this.setState({loading: true});
        const rowVersion = this.props.detail.rowVersion;
        abandonData(this.props.detail.id, rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    render() {
        const detailData = this.props.detail || {};
        const {options, planItemDetails, actualItemDetails, attachmentPresentations = [], attachmentInvoices = []} = detailData;
        const {formatMessage} = this.props.intl;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(options, PERMISSION.update))
            operations.push(<Button key="update" onClick={this.handleUpdateClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.edit',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.confirm) && hasPermissions(options, PERMISSION.confirm))
            operations.push(<Button key="confirm" onClick={this.handleConfirmClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.confirm',
                    defaultMessage: '确认'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.upInvoice) && hasPermissions(options, PERMISSION.upInvoice))
            operations.push(<Button key="upInvoice" onClick={this.handleUpInvoiceClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.upInvoice',
                    defaultMessage: '上传发票'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.invoiceConfirm) && hasPermissions(options, PERMISSION.invoiceConfirm))
            operations.push(<Button key="invoiceConfirm" onClick={this.handleInvoiceConfirmClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.invoiceConfirm',
                    defaultMessage: '发票确认'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.writeOff) && hasPermissions(options, PERMISSION.writeOff))
            operations.push(<Button key="writeOff" onClick={this.handleWriteOffClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.writeOff',
                    defaultMessage: '核销'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(options, PERMISSION.submit))
            operations.push(
                <WrappedPopconfirm
                    id="submit"
                    key="submit"
                    title={formatMessage({
                        id: 'detailPanel.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    onConfirm={this.submitConfirm}>
                    <Button key="submit" size="small">{
                        formatMessage({
                            id: 'detailPanel.btn.submit',
                            defaultMessage: '提交'
                        })
                    }</Button>
                </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(options, PERMISSION.approve))
            operations.push(<Button key="approve" onClick={this.handleApproveClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.approve',
                    defaultMessage: '审核'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(options, PERMISSION.abandon))
            operations.push(
                <WrappedPopconfirm
                    id="abandon"
                    key="abandon"
                    title={formatMessage({
                        id: 'detailPanel.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    onConfirm={this.abandonConfirm}>
                    <Button key="abandon" size="small">{
                        formatMessage({
                            id: 'detailPanel.btn.abandon',
                            defaultMessage: '作废'
                        })
                    }</Button>
                </WrappedPopconfirm>);
        const columns = [{
            title: formatMessage({
                id: 'detailPanel.column.num',
                defaultMessage: '序号'
            }),
            dataIndex: 'num',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.marketingActivityItemCategoryL1Name',
                defaultMessage: '项目类型'
            }),
            dataIndex: 'marketingActivityItemCategoryL1Name',
            render: (text, record) => `${text}/${record.marketingActivityItemCategoryL2Name}`
        }, {
            title: formatMessage({
                id: 'detailPanel.column.item',
                defaultMessage: '项目'
            }),
            dataIndex: 'item',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.amount',
                defaultMessage: '费用'
            }),
            dataIndex: 'amount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.address',
                defaultMessage: '网址'
            }),
            dataIndex: 'address',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.posts',
                defaultMessage: '发帖量'
            }),
            dataIndex: 'posts',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.reading',
                defaultMessage: '阅读量'
            }),
            dataIndex: 'reading',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.traffic',
                defaultMessage: '点击量'
            }),
            dataIndex: 'traffic',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.likes',
                defaultMessage: '点赞量'
            }),
            dataIndex: 'likes',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.commentVolume',
                defaultMessage: '评论量'
            }),
            dataIndex: 'commentVolume',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.forwardingVolume',
                defaultMessage: '转发量'
            }),
            dataIndex: 'forwardingVolume',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.remark',
                defaultMessage: '其他'
            }),
            dataIndex: 'remark',
        }];
        return (
            <div className="detail">
                <Card loading={this.state.loading}>
                    <DescriptionList size="large" title={<Row><Col span={12}>{
                        formatMessage({
                            id: 'detailPanel.card.title',
                            defaultMessage: '技术升级延期申请信息'
                        })
                    }</Col>
                    <Col className={`col-align-right ${styles.detail}`} span={12}>{operations}</Col>
                    </Row>}>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.code',
                            defaultMessage: '编号',
                        })}>{this.props.detail.code}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.brandCode',
                            defaultMessage: '品牌',
                        })}>({this.props.detail.brandCode}){this.props.detail.brandName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.marketingActivityCode',
                            defaultMessage: '营销活动编号',
                        })}>{this.props.detail.marketingActivityCode}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.currency',
                            defaultMessage: '币种',
                        })}>{conventEnumValueToString(currency, this.props.detail.currency)}</Description>
                        {!this.props.isDealerUser && <Description term={formatMessage({
                            id: 'detailPanel.data.dealerCode',
                            defaultMessage: '总代编号',
                        })}>{this.props.detail.dealerCode}</Description>}
                        <Description term={formatMessage({
                            id: 'detailPanel.data.theme',
                            defaultMessage: '主题',
                        })}>{this.props.detail.theme}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.statDate',
                            defaultMessage: '开始日期',
                        })}>{formatDateTime(this.props.detail.statDate, DATE_FORMAT)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.endDate',
                            defaultMessage: '结束日期',
                        })}>{formatDateTime(this.props.detail.endDate, DATE_FORMAT)}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.mainItemName',
                            defaultMessage: '计划主项目',
                        })}>{this.props.detail.mainItemName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.mainItemRemark',
                            defaultMessage: '计划主项目备注',
                        })}>{this.props.detail.mainItemRemark}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.actualMainItemName',
                            defaultMessage: '实际主项目',
                        })}>{this.props.detail.actualMainItemName}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.actualMainItemRemark',
                            defaultMessage: '实际主项目备注',
                        })}>{this.props.detail.actualMainItemRemark}</Description>
                        <Description term={formatMessage({
                            id: 'detailPanel.data.scope',
                            defaultMessage: '营销目标',
                        })}>{this.props.detail.scope}</Description>
                    </DescriptionList>
                </Card>
                <Card>
                    <DescriptionList title={formatMessage({
                        id: 'detailPanel.table.planItemDetails',
                        defaultMessage: '活动计划项目清单'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                            dataSource={planItemDetails}
                            {...TABLE} />
                    </DescriptionList>
                </Card>
                <Card>
                    <DescriptionList title={formatMessage({
                        id: 'detailPanel.table.actualItemDetails',
                        defaultMessage: '活动实际项目清单'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                            dataSource={actualItemDetails}
                            {...TABLE} />
                    </DescriptionList>
                </Card>
                {attachmentPresentations && attachmentPresentations.length >= 0
                    ? <Card><DescriptionList size="large" title={formatMessage({
                        id: 'detailPanel.card.attachmentPresentations',
                        defaultMessage: '报告附件'
                    })}>
                        {attachmentPresentations.map(item => (<Description key={item.id}>
                            <a onClick={this.onClickDownload} key="delete" data-id={item.filePath} data-applyid={item.fileName}>
                                {item.fileName}</a></Description>))}
                    </DescriptionList></Card>
                    : <Card><DescriptionList size="large" title={formatMessage({
                        id: 'detailPanel.content.noAttachment',
                        defaultMessage: '暂无附件'
                    })}>
                    </DescriptionList></Card>}
                {attachmentInvoices && attachmentInvoices.length >= 0
                    ? <Card><DescriptionList size="large" title={formatMessage({
                        id: 'detailPanel.card.attachmentInvoices',
                        defaultMessage: '发票附件'
                    })}>
                        {attachmentInvoices.map(item => (<Description key={item.id}>
                            <a onClick={this.onClickDownload} key="delete" data-id={item.filePath} data-applyid={item.fileName}>
                                {item.fileName}</a></Description>))}
                    </DescriptionList></Card>
                    : <Card><DescriptionList size="large" title={formatMessage({
                        id: 'detailPanel.content.noAttachment',
                        defaultMessage: '暂无附件'
                    })}>
                    </DescriptionList></Card>}
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.state.loading}
                        onClick={this.props.onCancel}>{formatMessage({
                            id: 'detailPanel.btn.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    detail: PropTypes.object.isRequired,
    id: PropTypes.string.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    successReturn: PropTypes.func,
};

import {connect} from 'react-redux';
import {getDetail, tableSearch} from './actions';
import {injectIntl} from './intl';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);
const mapStateToProps = (state, props) => ({
    id: props.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    isDealerUser: state.getIn((['page', 'domainData', 'init', 'isDealerUser'])),
    permissions: getPermissions(state),
    detail: getDetailData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    init: () => dispatch(getDetail(props.id)),
    onCancel: () => {
        props.history.push(routes.query.url());
    },
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
